<template>
	<view style="width: 100%; height: 100%;background-color: #70552d;color: #fff;">
		<view :style="{height: sConf.tH+'px'}"></view>
		<view style="padding: 10px;">
			<tn-form :model="curData" label-position="top">
				<tn-form-item label="姓名" prop="name">
					<tn-input custom-class="gl-base-input" v-model="curData.name" type="text"
						@change="nameChange"></tn-input>
				</tn-form-item>
				<tn-form-item label="身份证号" prop="idcard">
					<tn-input custom-class="gl-base-input" v-model="curData.idcard" type="idcard"
						@change="idcardChange"></tn-input>
				</tn-form-item>
				<tn-form-item label="身份证人像面 (点击图片上传)" prop="photoa">
					<view style="display: flex;justify-content: center;">
						<image class="gl-idcard-image" :src="sConf.pics + curData.photoa" mode="scaleToFill"
							@click="upPhotoa"></image>
					</view>
				</tn-form-item>
				<tn-form-item label="身份证国徽面 (点击图片上传)" prop="photob">
					<view style="display: flex;justify-content: center;">
						<image class="gl-idcard-image" :src="sConf.pics + curData.photob" mode="scaleToFill"
							@click="upPhotob"></image>
					</view>
				</tn-form-item>
			</tn-form>

			<view v-if="curData.status === 0">
				<view style="padding: 15px;">
					<button class="gl-button-base" hover-class="gl-button-base-hover"
						:disabled="curData.status === 0 || !agent"> 等待审核 </button>
				</view>
			</view>
			<view v-else-if="curData.status === 1">
				<view style="padding: 15px;">
					<button class="gl-button-base" hover-class="gl-button-base-hover"
						:disabled="curData.status === 1 || !agent"> 认证完成 </button>
				</view>
			</view>
			<view v-else>
				<view style="padding: 15px;">
					<tn-checkbox v-model="agent" checked-shape="circle">我已知晓以上信息仅作为平台内用户身份实名认证，不得另作他用。</tn-checkbox>
				</view>
				<view style="padding: 15px;color:#dd524d" v-if="curData.status === 2">
					{{curData.desc}}
				</view>
				<view style="padding: 15px;">
					<button class="gl-button-base" hover-class="gl-button-base-hover"
						:disabled="curData.status === 1 || !agent" @click="submitForm"> 提交审核 </button>
				</view>
			</view>

		</view>
		<!-- 顶部自定义导航 -->
		<tn-navbar :placeholder="true" fixed bg-color="#70552d" text-color="#f3eacd"> {{title}}
		</tn-navbar>
	</view>
</template>

<script>
	import psMethod from '@/common/psMethod';
	import UniToCos from '../js_sdk/com-ls-cos/components/ls-cos'
	export default {
		data() {
			return {
				title: ' 实名认证',
				sConf: getApp().globalData,
				curData: {
					id: null,
					name: null,
					idcard: null,
					photoa: '/media/default/photoa.png',
					photob: '/media/default/photob.png',
					create: null,
					status: null,
					desc: null
				},
				warn: 0,
				agent: false,
			}
		},
		onLoad() {
			this.loadDataIdcodeList()
		},
		methods: {
			nameChange(e) {
				console.log('nameChange', e);
			},
			idcardChange(e) {
				console.log('idcardChange', e);
			},
			async upPhotoa() {
				if (this.curData.status === 0 || this.curData.status === 1) {
					return
				}
				let url = await this.avatarCosUpload()
				this.curData.photoa = url
				console.log('a面', url);
			},
			async upPhotob() {
				if (this.curData.status === 0 || this.curData.status === 1) {
					return
				}
				let url = await this.avatarCosUpload()
				this.curData.photob = url
				console.log('b面', url);
			},
			async avatarCosUpload() {
				let photo = await uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera']
				})
				console.log('选择的照片', photo);
				let token = await this.hasCosToken()
				console.log('cos token', token);
				let url = await this.hasCosUpload(token, photo.tempFilePaths[0])
				console.log('cosUpload', url);
				return url
			},
			hasCosToken() {
				let that = this
				return new Promise((resolve, reject) => {
					uni.request({
						url: that.sConf.host + '/api/cosSt/',
						method: 'POST',
						header: {
							'content-type': 'application/json',
							'authorization': that.sConf.token
						},
						data: {},
						success(res) {
							console.log(res);
							if (res.data.rescode === 200 && res.data.resmsg) {
								resolve(res.data.resmsg)
							} else {
								reject("error")
							}
						},
						fail(err) {
							reject('error')
						}
					})
				})
			},
			hasCosUpload(cosDict, file) {
				return new Promise((resolve, reject) => {
					let cos = new UniToCos(cosDict.account.bucket, cosDict.account.region)
					// 传入secretId,secretKey,sessionToken
					cos.createCos(cosDict.credentials.tmpSecretId, cosDict.credentials
						.tmpSecretKey, cosDict.credentials
						.sessionToken)
					// 传入filePath和fileName
					let filePath = file;
					let fileName = 'media/idcard' + filePath.substr(filePath.lastIndexOf(
						'/'));
					cos.wxUploadFile(filePath, fileName).then(rec => {
						console.log("上传图片", rec.Location.substr(rec.Location
							.indexOf('/')))
						resolve(rec.Location.substr(rec.Location.indexOf('/')))
					})
				})
			},
			loadDataIdcodeList() {
				let host = this.sConf.host + '/weapps/idcard/'
				let token = this.sConf.token
				let data = {
					sid: this.sConf.auth.id
				}
				psMethod.authenticatorGetSync(host, token, data).then(res => {
					console.log('加载认证信息', res);
					if (res.count > 0) {
						this.curData = res.resmsg[0]
					}
				})
			},

			loadDataIdcodePost() {
				let host = this.sConf.host + '/weapps/idcard/'
				let token = this.sConf.token
				let data = this.curData
				data.sid = this.sConf.auth.id
				psMethod.authenticatorPostSync(host, token, data).then(res => {
					console.log('提交实名认证', res);
					this.curData = res.resmsg
					uni.showModal({
						title: '提交成功',
						content: '请等待审核完成',
						showCancel: false,
						success() {
							uni.navigateBack()
						}
					})
				})
			},
			loadDataIdcodePatch() {
				let host = this.sConf.host + '/weapps/idcard/' + this.curData.id + '/'
				let token = this.sConf.token
				let data = this.curData
				data.sid = this.sConf.auth.id
				psMethod.authenticatorPatchSync(host, token, data).then(res => {
					console.log('修改实名认证', res);
					this.curData = res.resmsg
					uni.showModal({
						title: '提交成功',
						content: '请等待审核完成',
						showCancel: false,
						success() {
							uni.navigateBack()
						}
					})
				})
			},
			submitForm() {
				console.log('submitForm', this.curData);
				if (!this.curData.name) {
					uni.showToast({
						icon: 'error',
						title: '姓名错误'
					})
					return
				}
				if (!psMethod.regular(this.curData.idcard)) {
					uni.showToast({
						icon: 'error',
						title: '身份证号码错误'
					})
					return
				}
				if (this.curData.photoa.indexOf('default') > 0 || this.curData.photob.indexOf('default') > 0) {
					uni.showToast({
						icon: 'error',
						title: '身份证照片错误'
					})
					return
				}
				if (!this.curData.id) {
					this.loadDataIdcodePost()
				} else {
					this.loadDataIdcodePatch()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.gl-idcard-image {
		width: 280px; // *8
		height: 175px; // *5
		border: 1px solid #000000;
		border-radius: 10px;
	}

	.warnView {
		border-color: #dd524d;
	}
</style>